import asyncio
from util import delay, async_timed
from PyCmpltrtok.common import sep
import time


@async_timed()
async def main_task():
    
    @async_timed()
    async def sub_task():
        print('Async sleep 1')
        asyncio.sleep(1)
    
    try:
        loop = asyncio.new_event_loop()
        loop.run_until_complete(sub_task())
    finally:
        sep('Close sub loop')
        loop.close()
        print('Sub loop closed')
        
    """
    Traceback (most recent call last):
    File "/home/peiyp2004/code/python_basic/exercise/lib/asyncio/as_book/ch2_asyncio_basics/ch2_8_1_create_loop/listing_2_21_create_loop.MOD-re-create.py", line 42, in <module>
        main()
    File "/home/peiyp2004/code/python_basic/exercise/lib/asyncio/as_book/ch2_asyncio_basics/ch2_8_1_create_loop/listing_2_21_create_loop.MOD-re-create.py", line 33, in main
        loop.run_until_complete(main_task())
    File "/home/peiyp2004/miniconda3/envs/p310xinfer/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
        return future.result()
    File "/home/peiyp2004/code/python_basic/exercise/lib/asyncio/as_book/util/async_timer.py", line 16, in wrapped
        return await func(*args, **kwargs)
    File "/home/peiyp2004/code/python_basic/exercise/lib/asyncio/as_book/ch2_asyncio_basics/ch2_8_1_create_loop/listing_2_21_create_loop.MOD-re-create.py", line 17, in main_task
        loop.run_until_complete(sub_task())
    File "/home/peiyp2004/miniconda3/envs/p310xinfer/lib/python3.10/asyncio/base_events.py", line 625, in run_until_complete
        self._check_running()
    File "/home/peiyp2004/miniconda3/envs/p310xinfer/lib/python3.10/asyncio/base_events.py", line 586, in _check_running
        raise RuntimeError(
    RuntimeError: Cannot run the event loop while another loop is running
    sys:1: RuntimeWarning: coroutine 'main_task.<locals>.sub_task' was never awaited
    """
    
    return await delay(2, 'main_delay', interval=0.2)


def main():
    loop = asyncio.new_event_loop()
    
    try:
        print('sleep 1')
        time.sleep(1)
        sep('Will loop.run_until_complete')
        loop.run_until_complete(main_task())
    finally:
        sep('Close loop')
        loop.close()
        print('Loop closed')


if '__main__' == __name__:
    
    main()
    